import { getCode, reqRegister, getLogin, getUserInfo, loginOut } from "@/api"
// 登录与注册的仓库
export default {
  namespaced: true,
  actions: {
    // 获取验证码
    async getRegisterCode(context, phone) {
      let result = await getCode(phone)
      if (result.code === 200) {
        context.commit('GETREGISTERCODE', result.data)
      } else {
        return new Promise(new Error('failed'))
      }
    },
    // 用户注册
    async userRegister(context, data) {
      let result = await reqRegister(data)
      if (result.code === 200) {
        return 'ok!'
      } else {
        return Promise.reject(new Error('failed'))
      }
    },
    // 用户登录
    async getUserLogin(context, data) {
      let result = await getLogin(data)
      if (result.code === 200) {
        context.commit('GERUSERLOGIN', result.data.token)
        // 持久化且是最新的token
        localStorage.setItem('token', result.data.token)
        return 'ok!'
      } else {
        return Promise.reject(new Error('failed'))
      }
    },
    // 获取登录用户信息
    async getUserInfoByToken(context) {
      let result = await getUserInfo()
      if (result.code === 200) {
        context.commit('GETUSERINFOBYTOKEN', result.data)
        return 'ok'
      } else {
        return Promise.reject(new Error('failed'))
      }
    },
    // 退出登录
    async userLoginOut(context) {
      // 通知服务器退出登录
      let result = await loginOut()
      if (result.code === 200) {
        // 让mutations清空相应数据
        context.commit('USERLOGINOUT')
      }
    }
  },
  mutations: {
    GETREGISTERCODE(state, val) {
      state.codes = val
    },
    GERUSERLOGIN(state, val) {
      state.token = val
    },
    GETUSERINFOBYTOKEN(state, val) {
      state.userInfo = val
    },
    USERLOGINOUT(state) {
      state.userInfo = {}
      state.token = ''
    }
  },
  state: {
    codes: '',
    // 服务下发的token，是身份验证的唯一标识符
    token: localStorage.getItem('token'),
    userInfo: {}
  },
  getters: {}
}